package com.key.w8.common.util;

import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * @Author: k8
 * @CreateTime: 2025-04-25
 * @Version: 1.0
 */
public class IpUtil {
    public static String resolveIp(String urlString) {
        try {
            URL url = new URL(urlString);
            String host = url.getHost();
            InetAddress address = InetAddress.getByName(host);
            return address.getHostAddress();
        } catch (Exception e) {
            throw new RuntimeException("无法解析 IP 地址: " + urlString, e);
        }
    }

    /**
     * 从 URL 中解析出端口，如果没显式指定就返回默认的 HTTP/HTTPS 端口
     */
    public static int resolvePort(String urlString) {

        try {
            URL url = new URL(urlString);
            int port = url.getPort();
            if (port == -1) {
                // 未显式指定端口，返回协议默认端口
                return url.getProtocol().equalsIgnoreCase("https") ? 443 : 80;
            }
            return port;
        } catch (MalformedURLException e) {
            throw new RuntimeException("无法解析端口: " + urlString, e);
        }
    }
    public static String resolveHost(String urlString) {
        if(urlString.startsWith("https://")){
            if (urlString.length() == 8) return "";
            else return urlString.substring(8);
        }else if (urlString.startsWith("http://")){
            if (urlString.length() == 7) return "";
            else return urlString.substring(7);
        }
        return urlString;
    }
}
